﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using WZN_shop.Models;
using WZN_shop.Models.Database;
using WZN_shop.service;

namespace WZN_shop.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class OrderControllers : ControllerBase
    {
        private readonly IJWTService _jwtService;
        private readonly WZN_ShopContext _db;
        public OrderControllers(IJWTService jwtService, WZN_ShopContext db)
        {
            _jwtService = jwtService;
            _db = db;
        }



        /// <summary>
        /// 结算接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public string OrderSettlement()
        {
            //获取用户id
            var userId = int.Parse(Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
            var carItem = _db.ShopCars.Where(x => x.UserId == userId).ToList();
            if (carItem == null)
            {
                return "购物车为空";
            }
            var orderid = _db.Porders.Select(x => x.OrderId).Max();
            orderid++;
            //创建订单详细表
            var orderDetil = new List<OrderDetil>();
            //OrderDetil orderDetil=new OrderDetil();
            decimal realutPrice = 0;
            foreach (var item in carItem)
            {
                var good = _db.Goods.FirstOrDefault(x => x.GoodId == item.GoodId);
                if (good == null)
                {
                    return "商品不存在";
                }
                if (item.Count > good.GoodInventory)
                {
                    return "库存不足";
                }
                good.GoodInventory -= item.Count;
                OrderDetil OrderDetil1 = new OrderDetil();

                OrderDetil1.OrderId = orderid;
                OrderDetil1.GoodId = good.GoodId;
                OrderDetil1.Count = item.Count;
                OrderDetil1.Price = good.GoodPrice * item.Count;
                OrderDetil1.UnitPrice = good.GoodPrice;
                realutPrice+= good.GoodPrice * item.Count;
                orderDetil.Add(OrderDetil1);

            }

            //创建订单总表
            Porder porder=new Porder();
            porder.OrderId = orderid;
            porder.UserId = userId;
            porder.Ostatic = "待发货";
            porder.Price = realutPrice;
            //为数据库添加订单详细
            _db.OrderDetils.AddRange(orderDetil);
            //删除数据库中用户存在在购物车上的信息
            _db.ShopCars.RemoveRange(carItem);
            //添加总订单
            _db.Porders.Add(porder);

            if (_db.SaveChanges()>0)
            {
                return "结算成功";
            }
            else
            {
                return "结算失败";
            }
           
        }



        /// <summary>
        /// 用户订单列表
        /// </summary>
        /// <param name="ostatic"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public IActionResult OrderList(string ostatic)
        {
            var userId = int.Parse(Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value);
            var orderList=_db.Porders.Where(x=>x.Ostatic==ostatic&&x.UserId==userId).ToList();
            if (orderList == null)
            {
                return BadRequest();
            }
            List<UserOrderViewModel> orderViewModels = new List<UserOrderViewModel>();
            foreach (var order in orderList)
            {
                var orderItems=_db.OrderDetils.Where(x=>x.OrderId==order.OrderId).ToList();
                List<Good> goods=new List<Good>(); 
                foreach(var item in orderItems)
                {
                    goods.Add(_db.Goods.FirstOrDefault(x=>x.GoodId==item.GoodId));
                }
                UserOrderViewModel viewModel = new UserOrderViewModel
                {
                    Goods = goods,
                    TotalPrice = order.Price,
                    Status = order.Ostatic
                };
                orderViewModels.Add(viewModel);
            }
            return Ok(orderViewModels);

        }


        /// <summary>
        /// 后台订单列表
        /// </summary>
        /// <param name="orderid"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult OrderList(int orderid)
        {
            if (orderid == 0)
            {
                var orderlist = _db.Porders.ToList();

                if (orderlist == null)
                {
                    return BadRequest();
                }
                List<OrderList> orderList = new List<OrderList>();
                foreach (var order in orderlist)
                {
                    var orderitem = _db.OrderDetils.Where(x => x.OrderId == order.OrderId).ToList();
                    List<Good> goods = new List<Good>();
                    foreach (var item in orderitem)
                    {
                        goods.Add(_db.Goods.FirstOrDefault(x => x.GoodId == item.GoodId));
                    }
                    OrderList view = new OrderList
                    {
                        order = order.OrderId,
                        Price = order.Price,
                        userid = order.UserId,
                        goods = goods,
                    };
                    orderList.Add(view);

                }
                return Ok(orderList);
            }
            else
            {
                var orderlist = _db.Porders.Where(x=>x.OrderId==orderid).ToList();

                if (orderlist == null)
                {
                    return BadRequest();
                }
                List<OrderList> orderList = new List<OrderList>();
                foreach (var order in orderlist)
                {
                    var orderitem = _db.OrderDetils.Where(x => x.OrderId == order.OrderId).ToList();
                    List<Good> goods = new List<Good>();
                    foreach (var item in orderitem)
                    {
                        goods.Add(_db.Goods.FirstOrDefault(x => x.GoodId == item.GoodId));
                    }
                    OrderList view = new OrderList
                    {
                        order = order.OrderId,
                        Price = order.Price,
                        userid = order.UserId,
                        goods = goods,
                    };
                    orderList.Add(view);

                }
                return Ok(orderList);
            }
        }



        /// <summary>
        /// 后台发货功能
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="send"></param>
        /// <param name="sendnumber"></param>
        /// <returns></returns>
        [HttpPost]
        public string SendOrder(int orderid,string send,string sendnumber)
        {
            var order=_db.Porders.FirstOrDefault(x=>x.OrderId==orderid);
            order.Ostatic = "已发货";
            return "订单"+orderid+"已通过" + send + "发货，快递单号为：" + sendnumber;
        }
    }
}
